﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Xml;
using DE.Sdc.SharePoint.SPContentStructure.Common;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class Webs : HierarchicalElement<Web>, IImportDefinition<SPWeb, SPWeb>
    {
        private HierarchicalList<Web, Web> _items;

        public Webs()
        {
            Items = new HierarchicalList<Web, Web>();
        }

        [XmlElement("Web")]
        public HierarchicalList<Web, Web> Items
        {
            get { return _items != null ? _items : new HierarchicalList<Web, Web>(); }
            set
            {
                _items = value;
                _items.Owner = base.Parent;
            }
        }

        [XmlIgnore]
        public SPWeb UpdatedSPObject { get; internal set; }

        /// <summary>
        /// Updates, replaces or deletes views for a list
        /// </summary>
        /// <param name="web">The parent list where to update, replace or delete the views</param>
        /// <param name="parentWeb"></param>
        public void ImportDefinition(SPWeb web, SPWeb parentWeb)
        {
            foreach (Web childWeb in Items)
            {
                Web subWebDefinition = childWeb;
                string subWebTitle = DeploymentHelper.Resolve(subWebDefinition.Title, web.Locale);
                string subWebUrl = DeploymentHelper.GetRootedUrl(DeploymentHelper.Resolve(subWebDefinition.Url, web.Locale), web.ServerRelativeUrl);

                SPWeb subWeb = !string.IsNullOrEmpty(subWebUrl)
                                   ? web.Site.OpenWeb(subWebUrl)
                                   : web.Webs[subWebTitle];
                subWebDefinition.ImportDefinition(subWeb.Exists ? subWeb : null, web);

                subWeb.Dispose();
            }

            UpdatedSPObject = web;
        }
    }
}